<template>
  <app-navbar />
  <div class="game-library-layout">
    <side-bar v-if="isLoggedIn" />
    <div class="game-library-view">
      <h2>我的游戏库</h2>
      <div v-if="loading" class="loading-spinner">
        <div class="spinner"></div>
      </div>
      <div v-else>
        <div v-if="games.length === 0" class="empty-tip">暂无游戏记录</div>
        <div class="game-library-list">
          <div v-for="game in games" :key="game.id" class="game-card">
            <div class="card-bg-glow"></div>
            <img :src="game.trailerPicture" class="game-cover" />
            <div class="game-info">
              <h3>{{ game.title }}</h3>
              <div class="game-meta">
                <span class="game-type">{{ game.genre }}</span>
                <span class="game-platform">{{ game.platforms }}</span>
                <span :class="['game-status', game.status === '1' ? 'owned' : 'not-owned']">
                  {{ game.status === '1' ? '已拥有' : '未拥有' }}
                </span>
              </div>
              <div class="game-details">
                <div><b>订单号：</b>{{ game.orderCode }}</div>
                <div><b>购买价格：</b>￥{{ game.buyPrice }}</div>
                <div><b>购买时间：</b>{{ formatTime(game.buyTime) }}</div>
                <div><b>游戏编号：</b>{{ game.gameCode }}</div>
              </div>
              <div class="game-actions">
                <button class="launch-btn" v-if="game.status === '1'">启动</button>
                <button class="buy-btn" v-else>购买</button>
                <button class="detail-btn" @click="showDetail(game)">详情</button>
              </div>
            </div>
          </div>
        </div>
        <div class="pagination-bar" v-if="total > pageSize">
          <button @click="goPage(page-1)" :disabled="page===1">上一页</button>
          <span>第 {{ page }} / {{ totalPages }} 页</span>
          <button @click="goPage(page+1)" :disabled="page===totalPages">下一页</button>
        </div>
      </div>
      <transition name="fade">
        <div v-if="detailGame" class="game-detail-modal" @click.self="detailGame=null">
          <div class="modal-content">
            <h2>{{ detailGame.title }}</h2>
            <img :src="detailGame.trailerPicture" class="modal-cover" />
            <ul>
              <li><b>订单号：</b>{{ detailGame.orderCode }}</li>
              <li><b>购买价格：</b>￥{{ detailGame.buyPrice }}</li>
              <li><b>购买时间：</b>{{ formatTime(detailGame.buyTime) }}</li>
              <li><b>游戏编号：</b>{{ detailGame.gameCode }}</li>
              <li><b>类型：</b>{{ detailGame.genre }}</li>
              <li><b>平台：</b>{{ detailGame.platforms }}</li>
              <li><b>状态：</b><span :class="['game-status', detailGame.status === '1' ? 'owned' : 'not-owned']">{{ detailGame.status === '1' ? '已拥有' : '未拥有' }}</span></li>
            </ul>
            <div class="comments-section">
              <h3>评论区</h3>
              <div v-if="gameComments.get(detailGame.id) && gameComments.get(detailGame.id).length > 0" class="comments-list">
                <div v-for="comment in gameComments.get(detailGame.id)" :key="comment.commentTime" class="comment-item">
                  <div class="comment-header">
                    <span class="comment-nickname">{{ comment.nickName }}</span>
                    <span class="comment-time">{{ formatTime(comment.commentTime) }}</span>
                  </div>
                  <div class="comment-content">{{ comment.commentContent }}</div>
                </div>
              </div>
              <div v-else class="no-comments">暂无评论</div>
            </div>
            <button class="close-btn" @click="detailGame=null">关闭</button>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import AppNavbar from '@/components/AppNavbar.vue'
import SideBar from '@/components/SideBar.vue'
import axios from '@/axios/axios'
import { webSocketService } from '@/websocket'

// 存储每个游戏的评论
const gameComments = ref(new Map())

// 连接WebSocket
onMounted(() => {
  webSocketService.connect('ws://localhost:8080/push')
  fetchGames(1)
})

// 组件卸载时断开WebSocket连接
onUnmounted(() => {
  webSocketService.disconnect()
})

const isLoggedIn = ref(localStorage.getItem('isLoggedIn') === 'true')
const games = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(9)
const loading = ref(false)
const detailGame = ref(null)

const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

function formatTime(time) {
  if (!time) return ''
  const d = new Date(time)
  return d.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

async function fetchGames(toPage = 1) {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:8080/buygame/list', {
      params: { page: toPage, pageSize: pageSize.value }
    })
    if (res.data && res.data.records) {
      games.value = res.data.records
      total.value = res.data.total || 0
      page.value = toPage
    } else {
      games.value = []
      total.value = 0
    }
  } catch (e) {
    games.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function goPage(toPage) {
  if (toPage < 1 || toPage > totalPages.value) return
  fetchGames(toPage)
}

function showDetail(game) {
  detailGame.value = game
  console.log('显示游戏详情:', game)
  
  // 确保gameId是字符串类型
  const gameId = String(game.id)
  
  // 如果还没有订阅这个游戏的评论，则订阅
  if (!gameComments.value.has(gameId)) {
    gameComments.value.set(gameId, [])
    console.log(`初始化游戏 ${gameId} 的评论列表`)
    
    // 订阅评论
    const unsubscribe = webSocketService.subscribe(gameId, (comment) => {
      console.log(`收到游戏 ${gameId} 的评论:`, comment)
      const comments = gameComments.value.get(gameId) || []
      comments.push({
        nickName: comment.nickName,
        commentContent: comment.commentContent,
        commentTime: comment.commentTime
      })
      // 更新引用以触发重新渲染
      gameComments.value.set(gameId, [...comments])
      console.log(`游戏 ${gameId} 的评论数更新为: ${comments.length}`)
    })

    // 在组件卸载时取消订阅
    onUnmounted(() => {
      unsubscribe()
      console.log(`取消游戏 ${gameId} 的订阅`)
    })
  }
}

// 已在上方的onMounted中调用过fetchGames(1)
// onMounted(() => {
//   fetchGames(1)
// })
</script>

<style scoped>
.game-library-layout {
  display: flex;
  flex-direction: row;
  width: 100vw;
  min-height: 100vh;
  background: linear-gradient(135deg, #181a20 60%, #232946 100%);
  justify-content: center;
}
.game-library-view {
  flex: 1;
  margin-left: 180px;
  padding: 56px 0 32px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
}
.game-library-view h2 {
  color: #a3b8d8;
  font-size: 2.4rem;
  margin-bottom: 36px;
  letter-spacing: 2px;
  text-shadow: 0 2px 18px #3a4a6a44, 0 0 2px #232946;
  font-weight: 700;
  transition: color 0.3s;
}
.game-library-list {
  display: flex;
  flex-wrap: wrap;
  gap: 40px 48px;
  justify-content: center;
  width: 90vw;
  max-width: 1400px;
}
.game-card {
  background: linear-gradient(135deg, rgba(35,41,70,0.97) 60%, rgba(78,140,255,0.10) 100%);
  border-radius: 22px;
  box-shadow: 0 6px 32px 0 #4e8cff22, 0 0 0 2px #232946;
  overflow: hidden;
  width: 340px;
  min-height: 440px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.3s, box-shadow 0.3s, border 0.3s;
  cursor: pointer;
  border: 2px solid transparent;
  position: relative;
  backdrop-filter: blur(1.5px);
  z-index: 1;
}
.card-bg-glow {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  z-index: 0;
  border-radius: 22px;
  pointer-events: none;
  background: radial-gradient(circle at 60% 40%, #4e8cff44 0%, transparent 70%);
  opacity: 0.7;
  transition: opacity 0.3s;
}
.game-card:hover {
  transform: translateY(-10px) scale(1.045);
  box-shadow: 0 12px 48px 0 #4e8cff55, 0 0 0 2.5px #4e8cff;
  border: 2px solid #4e8cff;
  z-index: 2;
}
.game-card:hover .card-bg-glow {
  opacity: 1;
}
.game-cover {
  width: 100%;
  height: 180px;
  object-fit: cover;
  display: block;
  filter: brightness(0.95) contrast(1.08);
  border-bottom: 1.5px solid #232946;
  z-index: 1;
}
.game-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 28px 18px 18px 18px;
  z-index: 1;
}
.game-info h3 {
  color: #e0e6f0;
  font-size: 1.25rem;
  margin-bottom: 16px;
  text-align: center;
  font-weight: 600;
  letter-spacing: 1px;
  text-shadow: 0 2px 12px #4e8cff33;
}
.game-meta {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  align-items: center;
  justify-content: center;
}
.game-type {
  color: #7fa7d6;
  font-size: 1.05rem;
  background: #232946;
  border-radius: 10px;
  padding: 4px 14px;
  font-weight: 500;
  box-shadow: 0 1px 6px #4e8cff22;
}
.game-platform {
  color: #6ed0ff;
  font-size: 1.05rem;
  background: #232946;
  border-radius: 10px;
  padding: 4px 14px;
  font-weight: 500;
  box-shadow: 0 1px 6px #4e8cff22;
}
.game-status {
  font-size: 1.05rem;
  border-radius: 10px;
  padding: 4px 14px;
  font-weight: 500;
  box-shadow: 0 1px 6px #4e8cff22;
  background: #232946;
  color: #7fa7d6;
  transition: background 0.2s, color 0.2s;
}
.game-status.owned {
  background: #4e8cff;
  color: #fff;
}
.game-status.not-owned {
  background: #444a5a;
  color: #bbb;
}
.game-details {
  margin: 10px 0 0 0;
  font-size: 0.98rem;
  color: #b0b3b8;
  width: 100%;
  text-align: left;
  line-height: 1.7;
  padding-left: 2px;
}
.game-actions {
  display: flex;
  gap: 14px;
  justify-content: center;
  margin-top: 16px;
}
.launch-btn {
  background: linear-gradient(90deg, #7fa7d6 0%, #4e8cff 100%);
  color: #232946;
  border: none;
  border-radius: 8px;
  padding: 8px 22px;
  font-size: 1.05rem;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 1px 6px #4e8cff22;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
}
.launch-btn:hover {
  background: linear-gradient(90deg, #4e8cff 0%, #7fa7d6 100%);
  color: #fff;
  box-shadow: 0 4px 16px #4e8cff55;
  transform: scale(1.05);
}
.buy-btn {
  background: linear-gradient(90deg, #4e8cff 0%, #6ed0ff 100%);
  color: #232946;
  border: none;
  border-radius: 8px;
  padding: 8px 22px;
  font-size: 1.05rem;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 1px 6px #4e8cff22;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
}
.buy-btn:hover {
  background: linear-gradient(90deg, #6ed0ff 0%, #4e8cff 100%);
  color: #fff;
  box-shadow: 0 4px 16px #4e8cff55;
  transform: scale(1.05);
}
.detail-btn {
  background: #232946;
  color: #7fa7d6;
  border: none;
  border-radius: 8px;
  padding: 8px 18px;
  font-size: 1.05rem;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 1px 6px #4e8cff22;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
}
.detail-btn:hover {
  background: #4e8cff;
  color: #fff;
  box-shadow: 0 4px 16px #4e8cff55;
  transform: scale(1.05);
}
.loading-spinner {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  width: 100%;
}
.spinner {
  border: 6px solid #e0e6f0;
  border-top: 6px solid #4e8cff;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.empty-tip {
  color: #7fa7d6;
  font-size: 1.2rem;
  margin: 40px 0;
  text-align: center;
}
.pagination-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 24px;
  margin: 36px 0 0 0;
}
.pagination-bar button {
  background: linear-gradient(90deg, #4e8cff 0%, #6ed0ff 100%);
  color: #232946;
  border: none;
  border-radius: 8px;
  padding: 8px 22px;
  font-size: 1.05rem;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 1px 6px #4e8cff22;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
}
.pagination-bar button:disabled {
  background: #444a5a;
  color: #bbb;
  cursor: not-allowed;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.game-detail-modal {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(24,26,32,0.92);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal-content {
  background: linear-gradient(135deg, #232946 60%, #4e8cff22 100%);
  border-radius: 18px;
  box-shadow: 0 8px 32px #4e8cff33;
  padding: 36px 32px 28px 32px;
  min-width: 340px;
  max-width: 90vw;
  color: #e0e6f0;
  position: relative;
  text-align: left;
  animation: modalPop 0.3s cubic-bezier(.4,0,.2,1);
}
@keyframes modalPop {
  0% { transform: scale(0.8); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}
.modal-content h2 {
  margin-bottom: 18px;
  color: #4e8cff;
  font-size: 2rem;
  text-align: center;
}

.comments-section {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #4e8cff22;
}

.comments-section h3 {
  color: #7fa7d6;
  font-size: 1.4rem;
  margin-bottom: 16px;
}

.comments-list {
  max-height: 240px;
  overflow-y: auto;
  padding-right: 8px;
}

.comment-item {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #4e8cff11;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.comment-nickname {
  color: #4e8cff;
  font-weight: 600;
}

.comment-time {
  color: #7fa7d6;
  font-size: 0.9rem;
}

.comment-content {
  color: #e0e6f0;
  line-height: 1.6;
}

.no-comments {
  color: #7fa7d6;
  text-align: center;
  padding: 16px 0;
}
.modal-cover {
  width: 100%;
  max-width: 320px;
  border-radius: 12px;
  margin: 0 auto 18px auto;
  display: block;
  box-shadow: 0 2px 16px #4e8cff33;
}
.modal-content ul {
  list-style: none;
  padding: 0;
  margin: 0 0 18px 0;
  font-size: 1.08rem;
}
.modal-content li {
  margin-bottom: 10px;
}
.close-btn {
  background: linear-gradient(90deg, #4e8cff 0%, #6ed0ff 100%);
  color: #232946;
  border: none;
  border-radius: 8px;
  padding: 8px 22px;
  font-size: 1.05rem;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 1px 6px #4e8cff22;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
  display: block;
  margin: 0 auto;
}
.close-btn:hover {
  background: linear-gradient(90deg, #6ed0ff 0%, #4e8cff 100%);
  color: #fff;
  box-shadow: 0 4px 16px #4e8cff55;
  transform: scale(1.05);
}
@media (max-width: 900px) {
  .game-library-view {
    padding: 24px 0 16px 0;
  }
  .game-library-list {
    width: 98vw;
    max-width: 100vw;
    gap: 24px 8px;
  }
  .game-card {
    width: 98vw;
    min-width: 180px;
    max-width: 100vw;
  }
}
</style>